package com.wolf.server;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;


import com.wolf.javabean.API;

//API服务采用发过即断的方式
public class APIMain implements Runnable{

	public static void main(String[] args) {
		runs();
	}
	
	public static void runs() {
		new Thread(new APIMain()).start();
	}
	
	public static int port = 8062;
	
	public void init(){
		ServerBootstrap boot = new ServerBootstrap();
		EventLoopGroup boss = null;
		EventLoopGroup worker = null;
		boss = new NioEventLoopGroup(2);
		worker = new NioEventLoopGroup(2);
		Class channelClass = NioServerSocketChannel.class;
		try{
			boot.group(boss, worker);
			boot.channel(channelClass);
			boot.childHandler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {//采用protobuf3作为传输的技术
					ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
					ch.pipeline().addLast(new ProtobufDecoder(API.ApiDatas.getDefaultInstance()));
					ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
					ch.pipeline().addLast(new ProtobufEncoder());
					ch.pipeline().addLast(new APIHandle());
				}
			}).option(ChannelOption.SO_BACKLOG, 256);
			System.out.println("启动服务:"+port);
			boot.bind(port).sync().channel().closeFuture().sync();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		init();
	}
	
}
